var _pagination = null;
//缓存 response
var _cache = null;
var _html = '';
var _imageUrl = '';
$(function() {

	$('.doubledate').kuiDate({
		className : 'doubledate',
		isDisabled : "0"
	});

	// 图片选择器 初始化
	browse('uploadImage', 'addImage', 96, 96);
	$("input[type='file']").change(function() {
		$(this).prev().prev().val($(this).val());
	});

	$('.doubledate').kuiDate({
		className : 'doubledate',
		isDisabled : "0" // isDisabled为可选参数，“0”表示今日之前不可选，“1”标志今日之前可选
	});
	initImage();

	initShopSelecter();
});

/**
 * 初始化店面选择器
 */
function initShopSelecter() {
	refreshInput($(".serWrapper"));
	$("#shopIsChoosed").removeAttr("checked");
	$("#shopName").attr("disabled", "disabled");

	$("#shopIsChoosed").bind("click", function() {
		var checked = $(this).attr("checked");
		if (checked) {
			$("#shopName").removeAttr("disabled");
		} else {
			$("#shopName").attr("disabled", "disabled");
			$("#shopName").empty();
		}
	});
}

/**
 * 栏目选择器
 */
function columnSelecter(self) {
	$(self).blur();
	initSelecter({
		method : 'get',
		url : '../column/selecter',
		heads : ["columnId", "columnName"],
		titles : ["栏目Id", "栏目名称"],
		zindex : 500,
		callBack : function(response, row) {
			var value = response.getValue('columnId', row);
			var key = response.getValue('columnName', row);
			var option = $("<option value='" + value + "'>" + key + "</option>");
			$(self).empty().append($(option));
		}
	});
}

//初始化图片查看组件
function initImage() {
	Shadowbox.init();
	window.openImage = function(url) {
		Shadowbox.open({
			content : url,
			player : 'img'
		});
	};
}

/**
 * 打开添加面板
 */
function openAddPanel() {
	_html = '';
	$("#addPanel input[type='text']").val('');
	$("#addPanel input[type='file']").val('');
	$("#addPanel textarea").val('');
	$("span#addImage > img").attr('src', "../images/img_activities1.jpg");

	$("#addOrUpdate").unbind("click");
	$("#addOrUpdate").bind("click", add);

	$("#addPanel").show();
	$("#yinying1").show();
	addMargin($("#addPanel"));
}

/**
 * 关闭添加面板
 */
function closeAddPanel() {
	$("#addPanel").hide();
	$("#yinying1").hide();
}

/**
 * 添加层 店面选择器
 */
function selectAddShop() {
	initSelecter({
		method : 'post',
		url : '../shop/find/shopList',
		heads : ["id", "name", "mp"],
		titles : ["店面ID", "店面名称", "电话"],
		zindex : 500, //缺省值
		callBack : callBack
	});

	function callBack(response, row) {
		var name = response.getValue('name', row);
		var shopId = response.getValue("id", row);
		$("#addShopName").val(name);
		$("#addShopId").val(shopId);
	}

}

function search() {

	var type = $("#type").val();
	var dates = $("#dates").val();
	_pagination = new Pagination({
		url : '../warnsetting/list',
		data : {
			type : type,
			dates : dates,
		},
		success : printListToPage,
		pagerHandler : 'pager'
	});
}

function printListToPage(rst) {
	//"messageId","shopID","shopName","typeName",
	//"title","content","imageUrl","url","status",
	//"status","keyword","effectDate","unEffectDate","count"
	var response = new qmsk.Response(rst);
	_cache = response;
	qmsk.dataTable({
		tbodyId : 'warnsettingList',
		heads : ["warntype", "dates","warnid"],
		response : response,
		sup : ['sup', '共 [index] 条'],
		handler : [[2, updateDeleteButton]]
	});
}

function del(warnid) {
	artConfirm('确定删除该条信息吗？', function() {
		qmsk.post('../warnsetting/delete/' + warnid, function(respones) {
			artSuccess("删除成功！");
			_pagination.reload();
		});
	});
}

function updateDeleteButton(warnid, row) {
	return "<input type='button' class='common_btn' value='修改' onclick=\"preUpdate(" + warnid + "," + row + ")\">" + "<input type='button' class='common_btn del' value='删除' onclick=\"del(" + warnid + "," + row + ")\">";
}

function add() {
	var warnType = $("#addwarnType").val();
	var dates = $("#adddates").val();
	var effectDate = $("#effectDate").val();
	var unEffectDate = $("#unEffectDate").val();

	var data = {
		RemindItem: warnType,
		RemindDay: dates,
		StartDate: effectDate,
		EndDate: unEffectDate

	};
	var data = qmsk.cleanObject(data);

	$.ajaxFileUpload({
		url : "../warnsetting/insert",
		secureuri : false,
		data : data,
		fileElementId : "uploadImage",
		dataType : "json",
		type : "post",
		success : function(rst, status) {
			if (qmsk.isEmpty(rst)) {
				artError('服务器忙，请联系系统管理员！');
				return;
			}
			if ( typeof rst === "string") {
				rst = JSON.parse(rst);
			}
			var response = new qmsk.Response(rst);

			if (response.state === 0) {
				closeAddPanel();
				artAlert("添加成功！");
				_pagination.reload();
			} else if (response.state == 1) {
				artError(response.msg);
			} else {
				checkStateShowErrorMsgAndDealResult(JSON.stringify(rst));
			}
		}
	});
	console.log(JSON.stringify(data));
}

function preUpdate(warnid, row) {
	_warnid = warnid;
	//"messageId","shopID","shopName","typeName",
	//"title","content","imageUrl","url","status",
	//"status","keyword","effectDate","unEffectDate","count"
	var response = _cache;
	var RemindItem = response.getValue("warntype", row);
	var RemindDay = response.getValue("dates", row);
	var StartDate = response.getValue("startdate", row);
	var EndDate = response.getValue("enddate", row);
	editorHtml = '';
	_html = editorHtml;
	$("#addwarnType").val(RemindItem);
	$("#adddates").val(RemindDay);
	if (qmsk.isNotEmpty(StartDate)) {
		StartDate = StartDate.substring(0, 10);
	}
	if (qmsk.isNotEmpty(EndDate)) {
		EndDate = EndDate.substring(0, 10);
	}
	$("#effectDate").val(StartDate);
	$("#unEffectDate").val(EndDate);

	$("#addOrUpdate").unbind("click");
	$("#addOrUpdate").bind("click", update);

	$("#addPanel").show();
	$("#yinying1").show();
	addMargin($("#addPanel"));
}

function generateHtml() {
	var url = $("#Url").val();
	if (qmsk.isNotEmpty(html)) {
		url = getHtmlUrl(html);
	}

}

function update(args) {
	var RemindID = _warnid;
	var RemindItem = $("#addwarnType").val();
	var RemindDay = $("#adddates").val();
	var StartDate = $("#effectDate").val();
	var EndDate = $("#unEffectDate").val();

	var data = {
		RemindItem : RemindItem,
		RemindDay : RemindDay,
		StartDate : StartDate,
		EndDate : EndDate
	};
	var data = qmsk.cleanObject(data);
		qmsk.post('../warnsetting/update/' + RemindID, data, function(respones) {
			closeAddPanel();
			_pagination.reload();
			artSuccess("更新成功！");
		});
	$.ajaxFileUpload({
		url : "../warnsetting/update/" + RemindID,
		secureuri : false,
		data : data,
		fileElementId : "uploadImage",
		dataType : "json",
		type : "post",
		success : function(rst, status) {
			if (qmsk.isEmpty(rst)) {
				artError('服务器忙，请联系系统管理员！');
				return;
			}
			if ( typeof rst === "string") {
				rst = JSON.parse(rst);
			}
			var response = new qmsk.Response(rst);

			if (response.state === 0) {
				closeAddPanel();
				_pagination.reload();
				artSuccess("更新成功！");
			} else if (response.state == 1) {
				artError(response.msg);
			} else {
				checkStateShowErrorMsgAndDealResult(JSON.stringify(rst));
			}
		}
	});
}

function getHtmlUrl(html) {
	var url = '';
	$.ajax({
		type : "post",
		async : false,
		datatype : "JSON",
		url : "../htmlUtils/htmlFileGender",
		data : {
			'html' : html
		},
		success : function(rst) {
			if ( typeof rst === "string") {
				rst = JSON.parse(rst);
			}
			var response = new qmsk.Response(rst);
			url = response.getValue("url");
		}
	});
	return url;
}

function generateHtmlUrl() {
	var html = editorHtml;
	console.log("html:" + html);
	console.log("_html:" + _html);
	if (_html == html) {
		return;
	}
	var url = '';
	if (qmsk.isNotEmpty(html)) {
		url = getHtmlUrl(html);
	}
	$("#Url").val(qmsk.isEmpty(url) ? '' : url);
}
